﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BlogAppExt.Models
{
    /// <summary>
    /// View Model object for the main index view listing all the blog posts
    /// </summary>
    public class IndexVM
    {

        public List<PostPreview> PostList { get; set; }
        public IndexVM()
        {
            PostList = new List<PostPreview>();
        }

        private int currentIndex;
        private int indexStep = 3;
        private int postCount;

        public int GetPrevIndex()
        {
            int prevIndex = currentIndex - indexStep;

            if (prevIndex <= 0)
            {
                prevIndex = 0;
            }

            return prevIndex;
        }

        public int GetNextIndex()
        {
            int nextIndex = currentIndex + indexStep;
            if (nextIndex >= postCount)
            {
                nextIndex = currentIndex;
            }

            return nextIndex;

        }

        /// <summary>
        /// Loads the BlogPosts and Users into the VM
        /// Users will be attached to their correct posts
        /// </summary>
        /// <param name="posts">List of BlogPosts</param>
        /// <param name="users">List of Users</param>
        public void LoadPosts(List<BlogPost> posts, List<User> users, int currentIndex)
        {
            this.currentIndex = currentIndex;
            this.postCount = posts.Count();

            posts = posts.Skip(currentIndex).Take(indexStep).ToList();

            foreach (var p in posts)
            {
                string text = p.Text.Substring(0, Math.Min(30, p.Text.Length)) + "...";

                User user = users.Where(x => x.Id == p.UserId).FirstOrDefault();
                PostList.Add(new PostPreview(p.Id, user.Id, user.UserName + " - " + user.NameFirst + " " + user.NameLast, user.Image, p.Title, text));
            }
        }
    }
}